package user

import (
	"encoding/json"
	"gq_volunteer_platform/bean"
	"gq_volunteer_platform/model/admin"
	"gq_volunteer_platform/model/user"
	"gq_volunteer_platform/model/weixin"
	"io"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

func Code2token(c *gin.Context) {

	var req struct {
		Code string `binding:"required,lt=255"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		bean.Log.Warning(err)
		c.String(400, err.Error())
		return
	}

	// 查询凭证
	var one weixin.AccessToken
	if err := bean.MysqlDb.Where("id=?", 1).First(&one).Error; err != nil {
		bean.Log.Warning(err)
		c.String(400, "数据不存在id=1")
		return
	}

	// 发送 http 请求
	var url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + one.Appid + "&secret=" + one.Secret + "&js_code=" + req.Code + "&grant_type=authorization_code"
	var body []byte
	if resp, err := http.Get(url); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	} else {
		defer resp.Body.Close()
		if b, err := io.ReadAll(resp.Body); err != nil {
			bean.Log.Error(err)
			c.String(500, err.Error())
			return
		} else {
			body = b
		}
	}

	// 解析
	var res struct {
		Openid     string `json:"openid"`
		SessionKey string `json:"session_key"`
		Unionid    string `json:"unionid"`
		Errcode    int    `json:"errcode"`
		Errmsg     string `json:"errmsg"`
	}

	if err := json.Unmarshal(body, &res); err != nil {
		bean.Log.Error(err)
		c.String(400, err.Error())
		return
	}

	// 判断是否成功
	if res.Errcode != 0 {
		bean.Log.Error(res.Errmsg)
		c.String(400, res.Errmsg)
		return
	}

	// 判断用户是否存在，不存在则新增一个
	var two user.User
	if err := bean.MysqlDb.Where("`openid`=?", res.Openid).Limit(1).Find(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 新增用户
	if two.ID == 0 {
		// 新增用户
		two.Name = "微信用户"
		two.ProfilePhoto = "upload/profile.png"
		two.Openid = res.Openid
		two.LastIp = c.ClientIP()
		two.LastLoginTime = time.Now().Format(time.DateTime)
		two.CheckStatus = "待申请"
		two.ChangeStatus = "待申请"
		two.AllowNotice = "false"
		two.YearMonth = time.Now().Format("2006-01")

		if err := bean.MysqlDb.Create(&two).Error; err != nil {
			bean.Log.Warning(err)
			c.String(500, "数据库错误，请检查手机号码是否重复")
			return
		}
	}

	if err := two.NewToken(); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	two.LastIp = c.ClientIP()
	two.LastLoginTime = time.Now().Format(time.DateTime)

	if err := bean.MysqlDb.Save(&two).Error; err != nil {
		bean.Log.Warning(err)
		c.String(500, err.Error())
		return
	}

	c.PureJSON(200, two)
}

// 登录绑定的管理员账号
func LoginBindAdmin(c *gin.Context) {

	// 获取登录用户对象
	var u user.User
	if err := u.Get(c); err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	// 查询是否存在绑定的管理员账号
	var two admin.Admin
	if err := bean.MysqlDb.Where("`user_id`=?", u.ID).Limit(1).Find(&two).Error; err != nil {
		bean.Log.Error(err)
		c.String(500, err.Error())
		return
	}

	if two.ID == 0 {
		c.PureJSON(200, gin.H{
			"code": "请先绑定管理员账号",
		})
		return
	}

	c.PureJSON(200, gin.H{
		"code": "ok",
		"data": two,
	})
}
